import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @author xujian
 * Creation date 2024/2/19 15:48
 * @version 1.0
 */
public class Test {
    private final static String filePath = "C:\\Users\\toptea\\Desktop\\test";
    private final static String fileName = "xxxxxx";

    public static void main(String[] args) throws IOException {

//        for (int i= 0;i<2000;i++){
//            FileOutputStream fileOutputStream =  new FileOutputStream(new File(filePath,fileName.concat("(").concat(String.valueOf(i)).concat(")")));
//            fileOutputStream.write(1);
//            fileOutputStream.flush();
//            fileOutputStream.close();
//        }




        for (int j = 0 ;j<10;j++){
            File file = new File(filePath,fileName);

            System.out.println("createFile1 开始");
            long file1StartTime = System.currentTimeMillis();
            File file1 = createFile1(file);
            long file1EndTime = System.currentTimeMillis();

            System.out.println("createFile1 结束");
            System.out.println("createFile1 耗时------"+(file1EndTime-file1StartTime)+"毫秒---" +"文件名为:--"+file1.getName() );


            System.out.println("createFile2 开始");
            long file1StartTime2 = System.currentTimeMillis();
            File file2 = createFile2(file);
            long file1EndTime2 = System.currentTimeMillis();

            System.out.println("createFile2 结束");
            System.out.println("createFile2 耗时------"+(file1StartTime2-file1EndTime2)+"毫秒---" +"文件名为:--"+file2.getName() );
        }

    }

    private static File createFile1(File file){
        File tmpfile = file;
        int i = 1;
        while (true){
            if(!tmpfile.exists()){
                return tmpfile;
            }

            String name = file.getName();
            String newName = name.concat("(").concat(String.valueOf(i)).concat(")");
            i++;
            tmpfile = new File(file.getParentFile(),newName);
        }
    }

    private static File createFile2(File file) {
        File tmpfile = file;

        File parentFile = tmpfile.getParentFile();

        File[] files = parentFile.listFiles();

        Map<String, Integer> collect = Arrays.stream(files).collect(Collectors.toMap(file1 -> file1.getName(), file12 -> 1,
                        (integer, integer2) -> 1
                )
        );

        int i = 1;
        String fileName = tmpfile.getName();
        while (true) {
            if (!collect.containsKey(fileName)) {
                return new File(parentFile,fileName);
            }
            String name = file.getName();
            fileName = name.concat("(").concat(String.valueOf(i)).concat(")");
            i++;
        }

    }
}
